<template>
  <el-select
    :model-value="modelValue"
    clearable
    filterable
    @change="handleChange"
    v-bind="$attrs"
    class="autowidth_select"
  >
    <el-option
      label="全选"
      value="all"
      v-if="isSelectAll && allList.length > 0"
      @click.native="selectAll"
    ></el-option>
    <el-option
      v-for="item in allList"
      :key="item.valueField"
      :label="item[labelField]"
      :value="item[valueField]"
    />
  </el-select>
</template>

<script setup>
import * as othersData from "@/data";
const props = defineProps({
  modelValue: {
    type: [String, Number, Array], //默认值
    default: null,
  },
  type: {
    type: String, //类型
    default: null,
  },
  valueField: {
    type: String, //value:默认为value
    default: "value",
  },
  labelField: {
    type: String, //label:默认为label
    default: "label",
  },
  dataSourse: {
    type: [Array, Object], //数据源
    default: null,
  },
  isAll: {
    type: Boolean, //是否导出整个下拉数据
    default: false,
  },
  isSelectAll: {
    type: Boolean, //是否全选
    default: false,
  },
});
const emits = defineEmits(["update:modelValue", "changeItem", "changeAll"]);

const { modelValue, dataSourse, type } = toRefs(props);
const acvTypeVos = computed(() => {
  let obj = {};
  for (let key in othersData) {
    obj[key] = othersData[key].map((item) => ({
      [props.valueField]: item.value,
      [props.labelField]: item.label,
    }));
  }
  obj = {
    ...obj,
    acvTypeVos: undefined,
  };
  return obj;
});
const allList = computed(() => {
  if (Array.isArray(dataSourse.value)) {
    if (props?.isAll) emits("changeAll", dataSourse.value);
    return dataSourse.value;
  }
  if (type.value) {
    const options = acvTypeVos.value?.[type.value] || [];
    if (props?.isAll) emits("changeAll", options);
    return options;
  }
  return [];
});
const handleChange = (val) => {
  emits("update:modelValue", val);
  if (Array.isArray(val)) {
    const item = allList.value.filter((item) =>
      val.includes(item[props.valueField])
    );
    emits("changeItem", item);
    return;
  }
  const item = allList.value.find((item) => item[props.valueField] === val);
  emits("changeItem", item);
};

//全选
const selectAll = () => {
  let selectValue = [];
  let data = JSON.parse(JSON.stringify(allList.value));
  if (!modelValue.value || modelValue.value?.length < data?.length) {
    data?.map((item) => {
      if (item?.disabled) return;
      selectValue.push(item[props.valueField]);
    });
    selectValue = selectValue?.filter((item) => item != "all");
    handleChange(selectValue);
  } else {
    // 取消全选
    selectValue = [];
    handleChange(selectValue);
  }
};
</script>
<style lang="scss" scoped>

</style>
